﻿using MCUPackage;
using MCUPackage.DesignEditor;
using MCUPackage.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace SxPackages.STC8.Models
{
	/// <summary>
	/// 定时器配置集合
	/// </summary>
	[Serializable]
	class AllTmrOptions
	{
		protected STC8HUSOP20 mParent = null;

		/// <summary>
		/// 所有定时器
		/// </summary>
		[Browsable(false),
		JsonIgnore]
		public TmrOptions[] All { get; private set; }
		/// <summary>
		/// 定时器0, 用于系统时钟
		/// </summary>
		[Browsable(false)]
		public TmrOptions Tmr0 { get; private set; }

		[Category("定时器配置"),
		DisplayName("定时器1"),
		TypeConverter(typeof(PropertySorter))]
		public TmrOptions Tmr1 { get; private set; }

		[Category("定时器配置"),
		DisplayName("定时器2"),
		TypeConverter(typeof(PropertySorter))]
		public TmrOptions Tmr2 { get; private set; }

		[Category("定时器配置"),
		DisplayName("定时器3"),
		TypeConverter(typeof(PropertySorter))]
		public TmrOptions Tmr3 { get; private set; }

		[Category("定时器配置"),
		DisplayName("定时器4"),
		TypeConverter(typeof(PropertySorter))]
		public TmrOptions Tmr4 { get; private set; }

		public AllTmrOptions(STC8HUSOP20 aParent)
		{
			mParent = aParent;
			this.Tmr0 = new TmrOptions(0, aParent);
			this.Tmr1 = new TmrOptions(1, aParent);
			this.Tmr2 = new TmrOptions(2, aParent);
			this.Tmr3 = new TmrOptions(3, aParent);
			this.Tmr4 = new TmrOptions(4, aParent);

			All = new TmrOptions[] { this.Tmr1, this.Tmr2, this.Tmr3, this.Tmr4 };
			this.Tmr0.Enable = true;
		}

		public bool AppendConfig(List<string[]> aLst)
		{
			string name = "Timer_Config";
			StringBuilder funcSb = new StringBuilder();
			funcSb.Append(TemplateHelper.GetFunctionCommit("定时器模块初始化"));
			funcSb.AppendLine($"PRIVATE void {name}(void)").AppendLine("{");
			funcSb.AppendLine("\tTIM_InitTypeDef attr;");

			funcSb.AppendLine();
			// 1ms中断
			this.Tmr0.Enable = true;
			this.Tmr0.Period = 1000;
			this.Tmr0.Priority = PriorityTypes.最高级;
			funcSb.AppendLine(this.Tmr0.Generate());

			foreach (var tmr in this.All)
			{
				string str = tmr.Generate();
				if (!string.IsNullOrEmpty(str))
				{
					funcSb.AppendLine();
					funcSb.AppendLine(str);
				}
			}

			funcSb.AppendLine("}");
			aLst.Add(new string[] { funcSb.ToString(), $"{name}();" });

			return true;
		}
	}
}
